package com.neuedu.yyzx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neuedu.yyzx.entity.User;
import com.neuedu.yyzx.framework.Res;
import com.neuedu.yyzx.service.IUserService;
import com.neuedu.yyzx.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PostMapping;

@RestController
public class LoginController {
    @Autowired
    IUserService userService;


    /**
     * http://localhost:8080/login
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Res login(@RequestBody User user){
        //1 验证用户名、密码是否正确
        Res result = null;
        User queryUser = getUserByPassword(user.getUsername(),user.getPassword());
        if(queryUser != null){
            String token = JWTUtils.encode(queryUser);
            result = Res.ok(token);
        }else{
            result = Res.failed(401,"用户名或者密码错误");
        }

        return  Res.ok(result);
    }


    /**
     * 根据用户名密码获取登录对象
     * @param username
     * @param password
     * @return
     */
    private  User getUserByPassword(String username,String password){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        queryWrapper.eq("password",password);
        return userService.getOne(queryWrapper);
    }
}
